package com.smsc.headend.task.engine.executor.impl.firmware;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.SystemClock;
import cn.hutool.json.JSONUtil;
import com.smsc.headend.common.enums.DeviceType;
import com.smsc.headend.common.enums.errorcode.TaskExecuteErrorCode;
import com.smsc.headend.common.utils.RedisUtils;
import com.smsc.headend.module.asset.dmo.ComConfigDMO;
import com.smsc.headend.module.asset.dmo.MeterConfigDMO;
import com.smsc.headend.module.asset.entity.ComEntity;
import com.smsc.headend.module.asset.entity.Meter;
import com.smsc.headend.module.common.entity.DeviceOperation;
import com.smsc.headend.module.data.dmo.DeviceSAPandKeys;
import com.smsc.headend.module.data.dto.DataItemDTO;
import com.smsc.headend.module.data.enums.DictionaryType;
import com.smsc.headend.module.fwu.entity.LogFwUpgradeHis;
import com.smsc.headend.module.fwu.entity.TemplateFwUpgrade;
import com.smsc.headend.module.protocol.ProtocolType;
import com.smsc.headend.module.protocol.cosem.util.ByteUtils;
import com.smsc.headend.module.task.dto.AtomicTask;
import com.smsc.headend.module.task.dto.Task;
import com.smsc.headend.task.engine.dao.TaskDAO;
import com.smsc.headend.task.engine.exception.UDISTaskExecutorException;
import com.smsc.headend.task.engine.executor.TaskExecutor;
import com.smsc.headend.task.engine.facade.DataItemFacade;
import com.smsc.headend.task.engine.handler.impl.firmware.ImageTransferVerifyAndActivationHandler;
import com.smsc.headend.module.task.dto.AtomicTaskState;
import com.smsc.headend.task.engine.service.ConnectorService;
import com.smsc.headend.task.engine.service.FeignAssetManagementService;
import com.smsc.headend.task.engine.service.asset.AssetService;
import com.smsc.headend.task.engine.service.firmware.FirmwareService;
import com.smsc.headend.task.engine.service.task.TaskPacketService;
import com.smsc.headend.task.engine.utils.AnsiUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author liangli
 * @date 2020/9/28
 */
public class FirmwareActivateExecutor implements TaskExecutor {
    @Autowired
    TaskPacketService packetService;
    @Autowired
    ConnectorService connectorService;
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    FeignAssetManagementService assetManagementRemoteService;
    @Autowired
    DataItemFacade dataItemFacade;
    @Autowired
    AssetService assetService;
    @Autowired
    TaskDAO taskDAO;
    @Autowired
    FirmwareService firmwareService;

    @Override
    public AtomicTaskState execute(Task task, AtomicTask atomicTask) throws UDISTaskExecutorException {

        DeviceOperation dictionary = assetService.getDictionary(atomicTask.getOperationId(), DictionaryType.Operation.getType());
        Meter meter = getMeter(task, assetService);
        if (task.getMeterId() != null && meter == null) {
            throw new UDISTaskExecutorException(TaskExecuteErrorCode.METER_NOT_EXISTS.toString());
        }
        ComEntity terminal = assetService.getComById(task.getComId());
        ComConfigDMO comConfigDMO = assetService.getComConfigById(task.getComId());
        List<DataItemDTO> dataItemDTOList = dataItemFacade.getDataItemsByOperation(meter, terminal, dictionary, getParameterMap(task, atomicTask), comConfigDMO.getModelId());
        if(comConfigDMO.getProtocolId() == ProtocolType.ANSI_C12_18_Protocol.getProtocolId()) {
            byte[] packets = packetService.ansiWriteFullTable(7, new byte[]{0x08, 0x0B, 0x00}, meter.getMeterId());
            log.debug(ByteUtils.byteToHexString(packets));
            connectorService.sendPacket(task, atomicTask, 2, task.getIsODR(), packets);
        } else {
            String interfaceType = comConfigDMO.getInterfaceType();
            Boolean isShortName = comConfigDMO.getIsShortName();
            MeterConfigDMO meterConfigDMO = null;

            if (!firmwareActivationExecutable(task, atomicTask, terminal)) {
                throw new UDISTaskExecutorException(TaskExecuteErrorCode.FW_UP_NOT_COMPLETE.toString());
            }

            if (task.getMeterId() != null) {
                meterConfigDMO = assetService.getMeterConfigById(task.getMeterId());
                interfaceType = meterConfigDMO.getInterfaceType();
                isShortName = meterConfigDMO.getIsShortName();
            }
            if (CollectionUtils.isEmpty(dataItemDTOList)) {
                throw new UDISTaskExecutorException(TaskExecuteErrorCode.DATAITEM_NOT_EXISTS.toString());
            }
            DeviceSAPandKeys deviceKeys = meter != null ? assetManagementRemoteService.getMeterCommunicationKey(meter.getMeterId(), dataItemDTOList.get(0).getRoleId()) :
                    assetManagementRemoteService.getTerminalCommunicationKey(terminal.getComId(), dataItemDTOList.get(0).getRoleId());
            byte[] packets = packetService.imageTransferActivation(dataItemDTOList.get(0), interfaceType, isShortName, deviceKeys.getWPort().intValue());
            connectorService.sendPacket(task, atomicTask, dataItemDTOList.get(0).getRoleId(), task.getIsODR(), packets);
        }

        AtomicTaskState state = taskDAO.hashGetAtomicTaskState(atomicTask.getAtomicTaskNo());
        if (state != null) {
            state.setStored(true);
            return state;
        }
        return createAtomicState(ImageTransferVerifyAndActivationHandler.class);

    }

    private boolean firmwareActivationExecutable(Task task, AtomicTask atomicTask, ComEntity comEntity) throws UDISTaskExecutorException {
        if (atomicTask.getSeq() > 0) {
            return true;
        }
        Long deviceType = null;
        Long deviceId = null;
        if (task.getMeterId() != null) {
            deviceType = DeviceType.METER.getId();
            deviceId = task.getMeterId();
        } else {
            deviceType = comEntity.getComDeviceType();
            deviceId = comEntity.getDeviceId();
        }

        Long taskPid = Convert.toLong(getParameterMap(task, atomicTask).get("taskPid"));
        Long taskId = Convert.toLong(getParameterMap(task, atomicTask).get("taskId"));

        if (taskPid == null) {
            log.info("firmware upgrade activation taskPid not exists");
            assetManagementRemoteService.saveFwuReport(deviceId, deviceType, null, taskId, TemplateFwUpgrade.TaskType.ImageActivation.getCode(), LogFwUpgradeHis.UpgradeResult.failed.getCode(),
                    null, SystemClock.now() / 1000, "previous task not exists");
            throw new UDISTaskExecutorException(TaskExecuteErrorCode.FW_UP_TASK_PID_NOT_EXISTS.toString());
        }
        LogFwUpgradeHis transferReport = assetManagementRemoteService.getFwuReport(deviceId, deviceType, taskPid, TemplateFwUpgrade.TaskType.ImageTransfer.getCode());
        if (transferReport != null && transferReport.getUpgradeResult() == LogFwUpgradeHis.UpgradeResult.success.getCode()) {
            return true;
        }

        log.info("firmware upgrade activation stop because of transfer failed. previous result={} ", JSONUtil.toJsonStr(transferReport));
        assetManagementRemoteService.saveFwuReport(deviceId, deviceType, null, taskId, TemplateFwUpgrade.TaskType.ImageActivation.getCode(), LogFwUpgradeHis.UpgradeResult.failed.getCode(),
                null, SystemClock.now() / 1000, "previous task failed");
        return false;
    }

    @Override
    public Boolean handleFailure(Task task, AtomicTask atomicTask, String message) {
        if (UDISTaskExecutorException.COM_STATUS_EXCEPTION.equalsIgnoreCase(message)) {
            log.warn("fwu activate pause because of com offline");
            return false;
        }
        firmwareService.saveFwuReport(task, atomicTask, -1, TemplateFwUpgrade.TaskType.ImageTransfer, "fwu activate execute failed", null);
        log.error("failExecuteActivate:{}", message);
        return true;
    }
}
